<!-- 购物车页面组件 -->
<template>
  <div class="shell" v-if="ifLoad"> <!-- 条件渲染，仅在数据加载完成时显示 -->
    <div class="cart-shell">
      <div class="cart-tit"><span>您的商品</span></div> <!-- 购物车标题 -->
      <div class="cart">
        <!-- 使用v-for循环渲染购物车中的商品列表 -->
        <div class="c-item" v-for="(v, i) in goods" :key="i">
          <div class="c-left">
            <!-- 商品图片 -->
            <img :src="`${v.photo}`" alt="" />
            <!-- 商品名称 -->
            <span class="c-tit">{{ v.gname }}</span>
          </div>
          <div class="operate">
            <!-- 商品价格 -->
            <span class="price">￥{{ v.price }}</span>
            <!-- 移除商品按钮 -->
            <button class="delete" @click="delGood(i, v.cid)">移除</button>
          </div>
        </div>
        <!-- 如果购物车为空，显示提示信息 -->
        <div class="blank" v-if="goods.length == 0">您的购物车空空如也 ~</div>
        <!-- 结算区域 -->
        <div class="buy">
          <div class="aprice">
            <!-- 显示总金额 -->
            <span>总金额：<span>￥ {{ total }}</span></span>
          </div>
          <!-- 结算按钮 -->
          <button
            :class="{ disable: goods.length == 0 }"
            :disabled="goods.length == 0"
            @click="pay"
          >
            结算<Coin class="icon" />
          </button>
          <!-- 清空购物车按钮 -->
          <button
            :class="{ disable: goods.length == 0 }"
            :disabled="goods.length == 0"
            class="del-all"
            @click="delAllGood"
          >
            清空购物车<Delete class="icon" />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElLoading } from "element-plus"; // 导入element-plus的加载组件

export default {
  data() {
    return {
      goods: [], // 商品列表
      ifLoad: true, // 数据加载标志
      ordId: [], // 订单ID数组
      loadingInstance: null, // 加载实例
    };
  },
  computed: {
    total() {
      var goods = this.goods;
      // 通过累加商品价格计算总金额
      var sum = 0;
      for (var item of goods) sum += item.price;
      return sum;
    },
  },
  methods: {
    // 获取购物车内商品
    async findCart() {
      const that = this;
      await that.$axios
        .get("cart/findCarts")
        .then((response) => {
          console.log('购物车',response);
          if (response.status != 200)
            return that.$tools.alertMsg("系统错误", "error");
          if (response.data.code == 200) {
            that.goods = response.data.data;
            that.goods.forEach((item, index) => {
              if(item.photo && !item.photo.startsWith('http')){
                item.photo = `${that.$store.state.baseUrl}/${item.photo}`;
              }
            });
          } else {
            that.$tools.alertMsg("获取商品失败", "error", 1500);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 删除商品
    async delGood(i, cid) {
      const that = this;
      const query = {
        cid: cid
      };
      await that.$axios
        .delete("cart/del", {data: query})
        .then((response) => {
          console.log(response);
          if (response.status != 200)
            return that.$tools.alertMsg("系统错误", "error");
          if (response.data.code == 200) {
            that.goods.splice(i, 1);
            that.$tools.alertMsg(response.data.message, "success");
          } else if(response.data.code == 404){
            that.$tools.alertMsg(response.data.message, "error");
          } else {
            that.$tools.alertMsg("移除商品失败", "error");
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 清除购物车
    async delAllGood() {
      const that = this;
      await that.$axios
        .delete("cart/delAll")
        .then((response) => {
          console.log(response);
          if (response.status != 200)
            return that.$tools.alertMsg("系统错误", "error");
          if (response.data.code == 200) {
            that.goods = [];
            that.$tools.alertMsg(response.data.message, "success");
          } else {
            that.$tools.alertMsg("清空购物车失败", "error");
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 创建购物车订单
    async createOrd() {
      var Gname = [];
      for (let item of this.goods) Gname.push({gid: item.gid});
      console.log(Gname)
      const that = this;
      await that.$axios
        .post("order/createCartOrders", Gname)
        .then((response) => {
          console.log(response);
          if (response.status != 200)
            return that.$tools.alertMsg("系统错误", "error");
          if (response.data.code == 200) {
            this.ordId = response.data.data;
          } else {
            that.$tools.alertMsg("创建订单失败", "error", 1500);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 结算订单
    async payoff() {
      const that = this;
      const oids = this.ordId;
      console.log(oids)
      let promises = oids.map((item) => {
        return that.$axios.post("mybox/saveMyBox", {oid: item.oid});
      });
      Promise.all(promises)
        .then(() => {
          that.goods = [];
          that.$tools.alertMsg("结算成功，游戏已入库", "success", 2000);
        })
        .catch((error) => {
          that.$tools.alertMsg("执行请求时发生错误，结算失败", "error");
        });
      that.loadingInstance.close();
      // 清空订单列表
      that.ordId = [];
    },
    // 购买游戏，下单+结算
    async pay() {
      const loadOptions = { text: "结算中", background: "rgba(23,29,37,0.7)" };
      this.loadingInstance = ElLoading.service(loadOptions);
      await this.createOrd();
      await this.payoff();
      this.loadingInstance.close();
    },
  },
  async created() {
    // const loadOptions = { text: "加载中", background: "rgba(23,29,37,0.7)" };
    // this.loadingInstance = ElLoading.service(loadOptions);
    await this.findCart();
    // this.loadingInstance.close();
    this.ifLoad = true;
  },
};
</script>

<style lang="less" scoped>
// 商品为空时禁用结算按钮
.disable {
  cursor: not-allowed !important;
  &:hover {
    background-color: #2b475e !important;
    color: #67c1f5 !important;
    .icon {
      color: #67c1f5 !important;
    }
  }
}
.icon {
  width: 18px;
  height: 18px;
  color: #67c1f5;
}
.shell {
  height: calc(100vh - 72px);
  .cart-shell {
    max-width: 960px;
    margin: 0px auto;
    height: 100%;
    background: linear-gradient(to right, #1a2a3c 2%, #233e5b, #1a2a3c 98%);
    padding: 10px;
    box-sizing: border-box;
    .cart-tit {
      text-align: left;
      color: #ddd;
      font-size: 26px;
      padding: 10px 10px;
    }
    .blank {
      color: #fff;
      height: 100px;
      font-size: 20px;
      line-height: 100px;
    }
    // 购物车商品样式
    .cart {
      padding: 10px 0px 20px 0px;
      border-top: 2px solid #1a3045;
      background: linear-gradient(
        to right,
        #1a2a3c 5%,
        #1d364d 15%,
        #204462,
        #1d364d 85%,
        #1a2a3c 95%
      );
      .c-item {
        padding: 8px 18px;
        display: flex;
        justify-content: space-between;
        background-color: #16202d;
        border-bottom: 6px solid #1b2838;
        .c-left {
          width: 50%;
          display: flex;
          img {
            width: 180px;
            height: 100px;
            object-fit: cover;
          }
          .c-tit {
            font-size: 19px;
            color: #ddd;
            margin-left: 20px;
            margin-top: 14px;
          }
        }
        .operate {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: flex-end;
          width: 40%;
          .price {
            color: #ddd;
            width: 100px;
          }
          .delete {
            width: 100px;
            height: 25px;
            background: none;
            text-decoration: underline;
            color: #7092a5;
          }
        }
      }
      .buy {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        color: #fff;
        margin-top: 20px;
        button {
          margin-left: 20px;
          width: 100px;
          height: 36px;
          color: #67c1f5;
          background-color: #2b475e;
          font-size: 16px;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          &:hover {
            background-color: #0a94e4;
            color: #fff;
            .icon {
              color: #fff;
            }
          }
        }
        .del-all {
          width: 130px;
          margin-left: 10px;
          &:hover {
            background-color: rgb(224, 12, 12);
          }
        }
      }
    }
  }
}
</style>
